package com.company.project.service.impl;

import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.dao.SysRoleAuthMapper;
import com.company.project.dao.SysRoleMapper;
import com.company.project.dao.SysUserMapper;
import com.company.project.model.RoleAuthDto;
import com.company.project.model.SysRole;
import com.company.project.model.SysRoleAuth;
import com.company.project.model.SysUser;
import com.company.project.service.SysRoleService;
import com.company.project.core.AbstractService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * Created by CodeGenerator on 2020/04/18.
 */
@Service
@Transactional
public class SysRoleServiceImpl extends AbstractService<SysRole> implements SysRoleService {
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRoleAuthMapper sysRoleAuthMapper;


    @Override
    public List<SysRole> getRoleListByUser(int userId) {
        return sysRoleMapper.getRoleListByUser(userId);
    }

    /**
     * 更改角色状态
     *
     * @param roleId
     * @param status
     * @return
     */
    @Override
    public Result changeStatus(int roleId, int status) {
        int result = sysRoleMapper.changeStatus(roleId,status);
        if (result > 0){
            return ResultGenerator.genSuccessResult();
        }else{
            return ResultGenerator.genFailResult();
        }
    }

    /**
     * 批量修改用户权限
     *
     * @param roleAuthDto
     * @return
     */
    @Override
    public Result batchUpdateRoleAuth(RoleAuthDto roleAuthDto) {
        Integer userId = roleAuthDto.getUserId();
        List<SysRole> roleList = roleAuthDto.getRoleList();
        List<SysRole> oldRoleList = getRoleListByUser(userId);
        if (!oldRoleList.isEmpty()){
            sysRoleMapper.deleteRoleByUser(userId);
        }
        for (SysRole role : roleList) {
            SysRoleAuth roleAuth = new SysRoleAuth();
            roleAuth.setRoleId(role.getId());
            roleAuth.setPartyId(userId);
            roleAuth.setPartyType((short)1);
            roleAuth.setCreateTime(new Date());
            roleAuth.setUpdateTime(new Date());
            roleAuth.setStatus((short)1);
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            roleAuth.setCreator(user.getId());
            roleAuth.setUpdator(user.getId());
            sysRoleAuthMapper.insert(roleAuth);
        }
        return ResultGenerator.genSuccessResult();
    }


}
